// https://github.com/shelljs/shelljs



var path = require('path')
var config = require('../config')
var ora = require('ora')
var webpack = require('webpack')
var proConfig = require('./proConfig')

var fs = require('fs');
console.log(
  '  Tip:\n' +
  '  Built files are meant to be served over an HTTP server.\n' +
  '  Opening index.html over file:// won\'t work.\n'
)

var spinner = ora('building for production...')
spinner.start()
var projectRoot = path.resolve(__dirname, '../') + "/"

var assetsPath = projectRoot + "dist"
// rm('-rf', assetsPath)
// mkdir('-p', assetsPath)
// cp('-R', 'static/*', assetsPath)
deleteTarget(assetsPath)
webpack(proConfig, function (err, stats) {
  spinner.stop()
  if (err) throw err
  process.stdout.write(stats.toString({
    colors: true,
    modules: false,
    children: false,
    chunks: false,
    chunkModules: false
  }) + '\n')
})


function deleteTarget(fileUrl) {
  // 如果当前url不存在，则退出
  if (!fs.existsSync(fileUrl)) return;
  // 当前文件为文件夹时
  if (fs.statSync(fileUrl).isDirectory()) {
    var files = fs.readdirSync(fileUrl);
    var len = files.length,
      removeNumber = 0;
    if (len > 0) {
      files.forEach(function (file) {
        removeNumber++;
        var stats = fs.statSync(fileUrl + '/' + file);
        var url = fileUrl + '/' + file;
        if (fs.statSync(url).isDirectory()) {
          deleteTarget(url);
        } else {
          fs.unlinkSync(url);
        }

      });
      if (removeNumber === len) {
        // 删除当前文件夹下的所有文件后，删除当前空文件夹（注：所有的都采用同步删除）
        fs.rmdirSync(fileUrl);
        console.log('删除文件夹' + fileUrl + '成功');
      }
    } else {
      fs.rmdirSync(fileUrl)
    }
  } else {
    // 当前文件为文件时
    fs.unlinkSync(fileUrl);
    console.log('删除文件' + fileUrl + '成功');
  }
}